﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Reflection;

namespace He.Common
{
    public class EnumHelper
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="enumType"></param>
        /// <returns></returns>
        public static List<ListItem> GetList(Type enumType)
        {
            if (enumType.IsEnum == false)
            {
                return null;
            }
            List<ListItem> list = new List<ListItem>();

            Type typeDescription = typeof(DescriptionAttribute);
            System.Reflection.FieldInfo[] fields = enumType.GetFields();
            string strText = string.Empty;
            string strValue = string.Empty;
            foreach (FieldInfo field in fields)
            {
                if (field.IsSpecialName) continue;
                strValue = field.GetRawConstantValue().ToString();
                object[] arr = field.GetCustomAttributes(typeDescription, true);
                if (arr.Length > 0)
                {
                    strText = (arr[0] as DescriptionAttribute).Description;
                }
                else
                {
                    strText = field.Name;
                }

                list.Add(new ListItem(strText, strValue));
            }

            return list;
        }

        /// <summary>
        /// 根据传入数值返回枚举值
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public static string GetEnumVal(object val, Type enumType)
        {
            Type typeDescription = typeof(DescriptionAttribute);
            System.Reflection.FieldInfo[] fields = enumType.GetFields();
            foreach (FieldInfo field in fields)
            {
                if (field.IsSpecialName) continue;
                if (field.GetRawConstantValue().ToString() == val.ToString())
                {
                    return field.Name;
                }
            }
            return string.Empty;
        }
    }
}
